import { ref, watch } from 'vue'

export default function useInput(props, emit, options) {
  const search = ref(props.value || '')
  const speed = (options && options.speed) || 120
  let delayTimer
  let num = 0
  watch(
    () => props.value,
    (val) => {
      if (search.value !== val) search.value = val
    }
  )
  async function handleInput() {
    num = 0
    clearInterval(delayTimer)
    delayTimer = setInterval(() => {
      if (num > 4) {
        emit('search', search.value)
        num = 0
        clearInterval(delayTimer)
      } else num++
    }, speed)
  }
  function handleChange() {
    emit('search', search.value)
  }
  function handleClear() {
    search.value = ''
  }
  return {
    search,
    handleInput,
    handleChange,
    handleClear
  }
}
